package com.xuan.yuapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.common.model.entity.InterfaceInfo;
import com.xuan.common.model.entity.User;
import com.xuan.common.model.entity.UserInterfaceInfo;
import com.xuan.yuapi.common.ErrorCode;
import com.xuan.yuapi.constant.CommonConstant;
import com.xuan.yuapi.exception.BusinessException;
import com.xuan.yuapi.mapper.UserInterfaceInfoMapper;
import com.xuan.yuapi.model.dto.user_interfaceinfo.UserInterfaceInfoQueryRequest;

import com.xuan.yuapi.service.InterfaceInfoService;
import com.xuan.yuapi.service.UserInterfaceInfoService;
import com.xuan.yuapi.service.UserService;
import com.xuan.yuapi.utils.SqlUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author 清凉茶
 * @description 针对表【user_interface_info】的数据库操作Service实现
 * @createDate 2024-05-22 10:39:32
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean isAdd) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer status = userInterfaceInfo.getStatus();
        if (status != null && (status > 1 || status < 0)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口状态错误");
        }

        Integer leftNum = userInterfaceInfo.getLeftNum();
        if (leftNum != null && leftNum < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口剩余调用次数不能小于0");
        }

        // 如果为首次添加用户-接口关系,这两个参数必须存在且合法
        if (isAdd) {
            Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
            Long userId = userInterfaceInfo.getUserId();
            if (interfaceInfoId == null || userId == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口id或用户id不能为空");
            }

            // 查询接口表
            QueryWrapper<InterfaceInfo> interfaceInfoQueryWrapper = new QueryWrapper<>();
            interfaceInfoQueryWrapper.eq("id", interfaceInfoId);
            long count = interfaceInfoService.count(interfaceInfoQueryWrapper);
            if (count < 1) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在");
            }

            // 查询用户表
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", userId);
            count = userService.count(userQueryWrapper);
            if (count < 1) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在不存在");
            }
        }
    }

    @Override
    public boolean invokeCount(Long interfaceInfoId, Long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 查看用户-接口关系表数据是否存在
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("interfaceInfoId", interfaceInfoId);
        queryWrapper.eq("userId", userId);
        UserInterfaceInfo userInterfaceInfo = this.getOne(queryWrapper);
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 更新调用总次数和剩余次数
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId", interfaceInfoId);
        updateWrapper.eq("userId", userId);
        updateWrapper.setSql("totalNum = totalNum + 1, leftNum = leftNum - 1");
        return this.update(updateWrapper);
    }


    @Override
    public QueryWrapper<UserInterfaceInfo> getQueryWrapper(UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest) {
        if (userInterfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long id = userInterfaceInfoQueryRequest.getId();
        Long interfaceInfoId = userInterfaceInfoQueryRequest.getInterfaceInfoId();
        Long userId = userInterfaceInfoQueryRequest.getUserId();
        Integer status = userInterfaceInfoQueryRequest.getStatus();
        Integer totalNum = userInterfaceInfoQueryRequest.getTotalNum();
        Integer leftNum = userInterfaceInfoQueryRequest.getLeftNum();
        String sortField = userInterfaceInfoQueryRequest.getSortField();
        String sortOrder = userInterfaceInfoQueryRequest.getSortOrder();

        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(interfaceInfoId != null, "interfaceInfoId", interfaceInfoId);
        queryWrapper.eq(userId != null && userId > 0, "userId", userId);
        status = Optional.ofNullable(status).orElse(0);
        queryWrapper.eq(status >= 0 && status <= 1, "status", status);
        queryWrapper.like(totalNum != null && totalNum >= 0, "totalNum", totalNum);
        queryWrapper.like(leftNum != null && leftNum >= 0, "leftNum", leftNum);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }
}




